package com.qianmi.xsite.render;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qianmi.xsite.render.domain.XSiteInfo;
import com.qianmi.xsite.render.domain.XSitePageRequest;
import com.qianmi.xsite.render.domain.XSitePageResponse;
import com.qianmi.xsite.render.util.HttpRequester;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 杨晓东[of1081]
 * @desc 满减营销活动。
 * @使用场景
 * @company qianmi.com
 * @Date 16/1/25
 **/
public class XSiteClient {


    private static Logger logger = LoggerFactory.getLogger(XSiteClient.class);

//    private static String hosts;
    //根据传入的host判断是那个环境信息

    //  private static String visitUrl  = "/${systemCode}/${userId}/${platForm}/${pageCode}";
    @Deprecated //建议使用带pageType的页面
    private static final String visitUrl  = "/%s/%s/%s/%s";
    // /${systemCode}/${userId}/${platForm}/${pageType}/${pageCode}
    private static final String serverRenderVisitUrl  = "/%s/%s/%s/%s/%s";
    ///d2cStore/check/A1217533/pc/[goodsInfo,goodsList,index]
    private static final String checkPageVisitUrl  = "/%s/check/%s/%s/%s";


    // /${systemCode}/${userId}/${platForm}/${pageType}/${pageCode}
    private static final String fullVisitUrl  = "/%s/%s/%s/%s/%s";


    //  http://oss-hz.qianmi.com/x-site/prod/d2cStore/A1129184/view/pc/index/index.html
    private static final String  aliVisitUrl  = "http://oss-hz.qianmi.com/x-site/%s/%s/%s/view/%s/%s/%s.html";

    private static final String VisitGlobalSetUpUrl  = "/%s/%s/pc/globalSetupco";

    private static final Map<String,String> envHost  = new HashMap<>();

    private static  int retryLimitCount = 3;

    /**
     * render服务器配置信息
     */
    private static String hostItem;


    /**
     * 环境信息, 由配置+预置配置得来
     */
    private static String envCode;

    /**
     *
     * @param hostConfigs 127.0.0.1:3001,127.0.0.1:3001
     * @param retryCount  重试获取数据次数，默认3次
     */
    public static void initConfig(String hostConfigs,int retryCount){
        retryLimitCount = retryCount;
        initConfigBy(hostConfigs);
    }

    public static void initConfig(String hostConfigs){
        initConfigBy(hostConfigs);
    }

    public static void initConfigBy(String hostConfigs){
        hostItem = hostConfigs.trim();
        if(envHost.size() == 0){
            XSiteClient.init();
        }

        String _envCode  ="prod";
        for(Map.Entry<String,String > value:envHost.entrySet()){
            if(org.apache.commons.lang3.StringUtils.isNotEmpty(value.getValue())&&value.getKey().equals(hostItem)){
                _envCode = value.getValue();
            }
        }
        if(_envCode==null){
            throw new Error("指定获取数据ip地址错误");
        }

        XSiteClient.envCode  = _envCode;
    }

    /**
     *
     * @param SystemCode
     * @param userId
     * @param platForm
     * @param pageCode
     * @deprecated 建议使用带pageType的
     * @return
     */
    public static String getPageContent(String SystemCode,String userId,String platForm,String pageCode){

        String content;
        try {
            String visitUrl  =XSiteClient.generateVisitUrl(SystemCode,userId,platForm,pageCode);
            content= get(visitUrl);
        } catch (Exception e) {
            logger.error("请求页面信息失败,尝试直接从阿里云拿" , e);
            String aliUrl  =String.format( XSiteClient.aliVisitUrl,envCode,SystemCode,userId,platForm,pageCode,pageCode);
            logger.warn("从阿里云请求页面URL::", aliUrl);
            content = HttpRequester.get(aliUrl, "UTF-8");
        }
        return content;
    }

    /**
     *
     * @param SystemCode
     * @param userId
     * @param platForm
     * @param pageType
     * @param pageCode
     * @return content
     */
    public static String getPage(String SystemCode,String userId,String platForm,String pageType,String pageCode){

        String content;
        try {
            String visitUrl  =XSiteClient.getVisitUrl(SystemCode, userId, platForm, pageType, pageCode);
            content= get(visitUrl);
        } catch (Exception e) {
            logger.error("请求页面信息失败,尝试直接从阿里云拿" , e);
            String aliUrl  =String.format( XSiteClient.aliVisitUrl,envCode,SystemCode,userId,platForm,pageType,pageCode);
            logger.warn("从阿里云请求页面URL::", aliUrl);
            content = HttpRequester.get(aliUrl, "UTF-8");
        }
        return content;
    }


    /**
     *
     * @param SystemCode
     * @param userId
     * @param platForm
     * @param pageType
     * @param pageCode
     * @return
     */
    public static String getPageHtml(String SystemCode,String userId,String platForm,String pageType,String pageCode,Map<String, String> paramsMap){

        XSitePageRequest xSitePageRequest = new XSitePageRequest(SystemCode, userId, platForm, pageType, pageCode);
        xSitePageRequest.setParamsMap(paramsMap);
        return XSiteClient.getPageHtml(xSitePageRequest).getContent();
    }

    /**
     * 请求获取参数  .
     * @param xSitePageRequest
     * @return
     */
    public static XSitePageResponse getPageHtml(XSitePageRequest xSitePageRequest){

        try {
            String visitUrl  =XSiteClient.generateFullVisitUrl(xSitePageRequest.getSystemCode(), xSitePageRequest.getUserId(), xSitePageRequest.getPlatForm(), xSitePageRequest.getPageType(), xSitePageRequest.getPageCode());
            return post(visitUrl, xSitePageRequest.getParamsMap(), xSitePageRequest.getHeadersMap());
        } catch (Exception e) {
            throw new Error("请求页面信息失败");
        }
    }




    /**
     * 生成访问URL
     * @param SystemCode    系统ID
     * @param userId        用户ID
     * @param platForm      平台属性
     * @param pageType      页面类型
     * @param pageCode      页面Code
     * @return  请求render URL
     */
    private static String getVisitUrl(String SystemCode,String userId,String platForm,String pageType,String pageCode){

        String visitUrl  =getOneHost() + String.format(XSiteClient.serverRenderVisitUrl, SystemCode, userId,platForm,pageType,pageCode);
        logger.info("从xsiteRender请求页面URL::",visitUrl);
        return  visitUrl;
    }
    /**
     * 生成访问URL
     * @param SystemCode
     * @param userId
     * @param platForm
     * @param pageCode
     * @return
     */
    private static String generateVisitUrl(String SystemCode,String userId,String platForm,String pageCode){

        String visitUrl  =getOneHost() + String.format(XSiteClient.visitUrl, SystemCode, userId,platForm,pageCode);
        logger.info("从xsiteRender请求页面URL::",visitUrl);
        return  visitUrl;
    }

    /**
     * 生成访问URL 带pageType的
     * @param SystemCode
     * @param userId
     * @param platForm
     * @param pageCode
     * @return
     */
   private static String generateFullVisitUrl(String SystemCode,String userId,String platForm,String pageType,String pageCode){

        String visitUrl  =getOneHost() + String.format(XSiteClient.fullVisitUrl, SystemCode, userId,platForm,pageType,pageCode);
        logger.info("从xsiteRender请求页面URL::",visitUrl);
        return  visitUrl;
    }


    /**
     * 获取服务端渲染访问URL
     * @param SystemCode
     * @param userId
     * @param platForm
     * @param pageCode
     * @return
     */
    private static String generateServerRenderVisitUrl(String SystemCode,String userId,String platForm,String pageCode){

        String visitUrl  =getOneHost() + String.format(XSiteClient.serverRenderVisitUrl, SystemCode,"render", userId,platForm,pageCode);
        logger.info("从xsiteRender请求页面URL::",visitUrl);
        return  visitUrl;
    }


    /**
     * 生成验证某个页面是否开启的访问URL
     *
        /d2cStore/check/A1217533/pc/[goodsInfo,goodsList,index]
     * @param SystemCode
     * @param userId
     * @param platForm
     * @param pageCode
     * @return
     */
    private static String generatePageCheckVisitUrl(String SystemCode,String userId,String platForm,String pageCode){
        String visitUrl  =getOneHost() + String.format(XSiteClient.checkPageVisitUrl, SystemCode, userId,platForm,pageCode);
        logger.info("从xsiteRender请求页面URL::",visitUrl);
        return  visitUrl;
    }


    /**
     * 获取
     * @param SystemCode
     * @param userId
     * @param platForm
     * @param pageCode
     * @return
     */
    public static String getServerRenderPagePost(String SystemCode, String userId, String platForm, String pageCode, Map<String, String> paramsMap){

        String content;
        try {
            String visitUrl  =XSiteClient.generateServerRenderVisitUrl(SystemCode, userId, platForm,pageCode);
            content= post(visitUrl, paramsMap, null).getContent();
        } catch (Exception e) {
            logger.error("请求页面信息失败,尝试直接从阿里云拿" , e);
            String aliUrl  =String.format( XSiteClient.aliVisitUrl,envCode,SystemCode,userId,platForm,pageCode,pageCode);
            logger.warn("从阿里云请求页面URL::", aliUrl);
            content = HttpRequester.get(aliUrl, "UTF-8");
        }
        return content;
    }

    /**
     * 检测下是否开启某页面
     *
     * @param systemCode
     * @param userId
     * @param platForm
     * @param pageTypes
     * @param pageCode
     * @return
     */
    public static boolean checkPageIsOpen(String systemCode, String userId, String platForm,String pageTypes, String pageCode) throws Exception {

        String visitUrl  =XSiteClient.generatePageCheckVisitUrl(systemCode, userId, platForm, pageCode);
        String content= get(visitUrl);
//        System.out.println(content);
        return content.indexOf("\"data\":true") > 0;
    }


    /**
     * 获取用户的建站配置    http://127.0.0.1:3001/d2cStore/A857570/pc/globalSetupco
     * @param SystemCode
     * @param userId
     * @return
     */
    public static XSiteInfo getPageSetUp(String SystemCode,String userId){

        String pageSetUp = null;
        XSiteInfo xSiteInfo = null;
        try {
            xSiteInfo = new XSiteInfo();
            String visitUrl  =getOneHost() + String.format(XSiteClient.VisitGlobalSetUpUrl, SystemCode, userId);
            logger.info("从xsiteRender请求页面站点配置::",visitUrl);
            pageSetUp= get(visitUrl);
            JSONObject jsonObject = JSON.parseObject(pageSetUp);
            xSiteInfo.setXsiteTitle(jsonObject.getString("siteTitle"));
            xSiteInfo.setXsiteGlobalStyle(jsonObject.getString("globalStyle"));
            xSiteInfo.setXsiteIconImgSrc(jsonObject.getString("siteIconImgSrc"));
            xSiteInfo.setXsiteTemplateCode(jsonObject.getString("templateCode"));
        }catch (Exception e){
            logger.error("请求页面站点配置信息失败");
        }
        return xSiteInfo;
    }




    private static void init(){
        envHost.put("172.19.65.20:3001", "test");
        envHost.put("192.168.65.222:18083","prod");
    }


    /**
     * 添加失败重试次数 retryLimitCount
     *
     * @return
     */
    private static String get(String visitUrl) throws Exception{
        int retryCount = 0;
        String result = null;
        while(result==null && retryCount<retryLimitCount){
            result= HttpRequester.get(visitUrl, "UTF-8");
            ++retryCount;
            if(retryCount==retryLimitCount && result==null){
                logger.error("第"+(retryLimitCount)+"次，已达到重试次数限制,请求"+visitUrl+"页面数据失败");
                throw new Exception("获取页面数据失败");
            }
        }
        return result;
    }

    /**
     *
     * @param visitUrl
     * @param paramsMap
     * @return
     */
    private static XSitePageResponse post(String visitUrl , Map<String, String> paramsMap,Map<String, String> headersMap) throws Exception{

        int retryCount = 0;
        XSitePageResponse response=null;
        while(response==null && retryCount<retryLimitCount){
            try {
                response=HttpRequester.post(visitUrl, paramsMap, headersMap);
                return response;
            }catch(Exception exception){
                logger.warn("请示页面数据发生错误:"+visitUrl,exception);
                ++retryCount;
                if(retryCount==retryLimitCount && response==null){
                    logger.error("第"+(retryLimitCount)+"次，已达到重试次数限制,请求"+visitUrl+"页面数据失败");
                    throw new Exception("获取页面数据失败，开始从阿里云获取数据");
                }
            }
        }
        return response;
    }


    private static String getOneHost(){
        return "http://"+hostItem;
    }
}
